package com.sto.stoapp.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;

/**
 * LED渐变视图
 * 
 * @author Administrator
 * 
 */
@SuppressLint({ "DrawAllocation", "HandlerLeak" })
public class LedScreenView extends View {

	// 默认颜色
	private static final int DEFAULT_COLOR = Color.BLACK;
	// 每次增加的高度
	private static final int DEFAULT_ADD_HEIGHT = 10;
	// 刷新间隔时间
	private static final int INTERVAL_TIME = 100;
	// 刷新屏幕
	private static final int UPDATE_SCREEN = 0xfd;

	// 屏幕宽高
	private int width, height;
	// 当前高度
	private int curHeight = 0;
	// 画笔
	private Paint mPaint;

	private OnScreenCompleteListener listener;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == UPDATE_SCREEN) {
				if (curHeight > height) {
					listener.onScreenCompleteListener();
				} else {
					invalidate();
				}
			}
		}

	};

	public LedScreenView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public LedScreenView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public LedScreenView(Context context) {
		super(context);
		init();
	}

	private void init() {
		mPaint = new Paint();
		mPaint.setColor(DEFAULT_COLOR);
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		this.width = w;
		this.height = h;
		new UpdateScreen().start();
		super.onSizeChanged(w, h, oldw, oldh);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Rect r = new Rect();
		r.top = 0;
		r.left = 0;
		r.right = width;
		r.bottom = curHeight;
		canvas.drawRect(r, mPaint);
	}

	class UpdateScreen extends Thread {
		@Override
		public void run() {
			super.run();
			while (curHeight < height) {
				if (curHeight + DEFAULT_ADD_HEIGHT >= height) {
					curHeight = height;
				} else {
					curHeight += DEFAULT_ADD_HEIGHT;
				}
				handler.sendEmptyMessage(UPDATE_SCREEN);
				try {
					Thread.sleep(INTERVAL_TIME);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			curHeight += DEFAULT_ADD_HEIGHT;
			handler.sendEmptyMessage(UPDATE_SCREEN);
		}
	}

	public void setListener(OnScreenCompleteListener listener) {
		this.listener = listener;
	}

	/**
	 * 监听屏幕刷新结束
	 * 
	 * @author Administrator
	 * 
	 */
	public interface OnScreenCompleteListener {
		void onScreenCompleteListener();
	}
	
	
	
}
